// pages/insurance/insurance.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    citys: ['南宁', '百色', '崇左'],
    // 存储用户的选择
    userChangeCity: null,
    // 页面状态类
    openCamera: false,
    codeText: '获取验证码',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  onShow: function () {

  },

  onHide: function () {

  },

  userChangeCity(e) {
    console.log(e)
    if (e.detail.value) {
      const index = Number(e.detail.value);
      this.setData({
        userChangeCity: this.data.citys[index],
      })
    }
  },
  shotBankCard(e) {
    this.setData({
      openCamera: true,
    })

  },
  closeCamera() {
    this.setData({
      openCamera: false,
    })
  },
  takePhoto(d) {
    console.log(d);
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'normal',
      success: (res) => {
        console.log(res)
      },
      fail: (e) => {
        console.log(e);
      },
      done: (d) => {
        console.log(d);
      }
    })
  },
  errorPhoto(e) {
    console.warn(e);
  },
  inputWord(e) {
    let val = e.detail.value.trim();
    let variabeName = e.currentTarget.dataset.name;
    this.setData({
      [variabeName]: val,
    })
  },
  askVCode() { // 获取短信验证码
    if (this.data.phone.length !== 11) {
      wx.showToast({
        title: '手机号码有误',
        icon: 'none',
        duration: 2000,
        mask: true,
      });
      return;
    }
    const testWord = '获取验证码';
    if (this.data.codeText === testWord) {
      this.setData({
        codeText: '验证码已发送'
      });
      let conutTime = 59;
      let reduceTime = setInterval(() => {
        this.setData({
          codeText: conutTime.toString() + '秒后再次发送'
        });
        conutTime--;
      }, 1000)
      setTimeout(() => {
        this.setData({
          codeText: '获取验证码'
        });
        clearInterval(reduceTime);
      }, conutTime * 1000)
      this.sendMsg();
    } else {
      // donothing
    }
  },
  sendMsg() { // 发送短信验证码
    wx.request({
      url: getApp().globalData.serverAddress + 'student/sendMsg',
      data: {
        userPhone: this.data.phone,
      },
      header: {
        Authorization: getApp().globalData.login.token,
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (res) { 
        if(res.data.code == 41){
          wx.showModal({
            title: '',
            content: res.data.message,
            showCancel: false,
            confirmText: '关闭',
            confirmColor: '',
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '发送验证码失败',
          content: JSON.stringify(res),
          showCancel: false,
          confirmText: '关闭',
          confirmColor: '',
        })
      },
      complete: function (res) { },
    })
  },
  showErrorModal(dat) {
    wx.showModal({
      title: '缺少内容',
      content: dat,
      showCancel: false,
      cancelText: '',
      cancelColor: '',
      confirmText: '知道了',
      confirmColor: '',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  buyInsurrance(e) {
    console.log('买保险');
    if (!this.data.userChangeCity) {
      this.showErrorModal('没有选择城市');
      return;
    }
    if (!this.data.phoneValidNumber || this.data.phoneValidNumber.length !== 6) {
      this.showErrorModal('验证码有误');
      return;
    }
    // if (!this.data.cardBank || !this.data.cardNumber || this.data.cardNumber.length < 10 || this.data.cardBank.length < 2) {
    //   this.showErrorModal('受益人银行信息不全');
    //   return;
    // }
    if (!this.data.beneficiary || this.data.beneficiary.length < 2) {
      this.showErrorModal('受益人名称不全');
      return;
    }
    if (!this.data.idNumber || this.data.idNumber.length < 14) {
      this.showErrorModal('请填写受益人身份证号');
      return;
    }
    // 提交步骤
    wx.showLoading({
      title: '',
      mask: true,
    })
    this.checkMsgValid()
      .then(d => {
        // console.log(d);
        return this.check4FactorBank();
      })
      .then(d => {
        // console.log(d);
        return this.createInsuranceOrder(d);
      })
      .then( d => {
        // console.log(d);
        const no = d.no;
        return this.callWxPay( no );
      })
      .then( d => {
        // console.log(d);
        return this.callWxPayService(d);
      })
      .then( d => {
        wx.hideLoading();
        wx.showToast({
          title: '支付成功',
          icon: '',
          duration: 1500,
          mask: true,
        });
        setTimeout(() => {
          wx.redirectTo({
            url: 'myInsurance',
          })
        }, 1501);
      })
      .catch(err => {
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          content: err,
          showCancel: false,
          confirmText: '关闭',
          confirmColor: '',
        })
      })
  },
  checkMsgValid() { // 检查验证码
    return new Promise((resl, rej) => {
      wx.request({
        url: getApp().globalData.serverAddress + 'student/checkMsg',
        data: {
          code: this.data.phoneValidNumber,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: function (res) {
          if (res.data.code == 0) {
            resl(res);
          } else {
            rej(res.data.message);
          }
        },
        fail: function (res) {
          rej('验证码验证失败，接口返回错误');
        },
        complete: function (res) { },
      })
    })
  },
  check4FactorBank(resl, rej) { // 检查三要素方法
    return new Promise((resl, rej) => {
      wx.request({
        url: 'https://ali-bankcard4.showapi.com/bank3',
        data: {
          acct_name: this.data.beneficiary,
          acct_pan: this.data.cardNumber,
          cert_id: this.data.idNumber,
          cert_type: '01',
          needBelongArea: true,
        },
        header: {
          Authorization: 'APPCODE 9afa1a6c2cd84662a3078ff976bcb6d3',
        },
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: function (res) {
          // console.log(res);
          if (res.statusCode == 555) {
            rej(res.data.showapi_res_body.msg)
          } else if (res.statusCode == 200 && res.data.showapi_res_body.msg === "认证通过") {
            resl(res.data.showapi_res_body.belong);
          } else {
            rej('验证没有通过')
          }
        },
        fail: function (res) {
          rej('未知错误')
        },
        complete: function (res) { },
      })
    })
  },
  createInsuranceOrder(bankInfo,resl,rej){
    return new Promise((resl,rej) => {
      let req = {
        bankName: bankInfo.bankName,
        encBankNo: bankInfo.cardNum,
        idCard: this.data.idNumber,
        insureId: '1126410280384737280',
        mobile: this.data.phone,
        name: this.data.beneficiary,
        password: "",
      }
      wx.request({
        url: getApp().globalData.serverAddress + 'student/createOrder',
        data: req,
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'POST',
        dataType: 'json',
        responseType: 'text',
        success: function(res) {
          if(res.data.code == 0){
            resl(res.data.data);
          }else{
            rej(JSON.stringify(res.data.message));
          }
        },
        fail: function(res) {
          rej('购买失败 ' + JSON.stringify(res.data))
        },
        complete: function(res) {},
      })
    })
  },
  callWxPay(num,resl,rej){
    return new Promise( (resl,rej) => {
      wx.request({
        url: getApp().globalData.serverAddress + 'pay/wxPay',
        data: {
          orderNum : num,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        success: function(res) {
          if(res.data.code === 0){
            resl(res.data.data);
          }else{
            rej(res.data.data);
          }
        },
        fail: function(res) {
          rej('创建支付失败 ' + JSON.stringify(res.data));
        },
        complete: function(res) {},
      })
    })
  },
  callWxPayService(dat,resl, rej){
    return new Promise( (resl,rej) => {
      wx.requestPayment({
        timeStamp: dat.timeStamp,
        nonceStr: dat.nonceStr,
        package: dat.packageStr,
        signType: dat.signType,
        paySign: dat.paySign,
        success: function(res) {        
          resl(true);
        },
        fail: function(res) {
          rej('调用微信支付失败 ' + JSON.stringify(res.data));
          // wx.redirectTo({
          //   url: 'myInsurance',
          // })
        },
        complete: function(res) {
          wx.hideLoading();
        },
      })
    })
  }
})